#pragma once

#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>
#include <cerrno>
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <functional>

namespace ns_Util{

    std::function<struct sockaddr*(void*)> _conv= [](void* addr){
        return (struct sockaddr*)addr;
    };
    void SetNonBlock(int fd)
    {
        int fl = fcntl(fd,F_GETFL);
        if(fl<0)
        {
            perror("fcntl错误");
            return ;
        }
        fcntl(fd,F_SETFL,fl | O_NONBLOCK);
    }
    int AcceptConnection(int sockfd, std::string* peerIp,uint16_t * peerPort)
    {
        struct sockaddr_in peer; 
        socklen_t len = sizeof(peer);

        int newsockfd = ::accept(sockfd,_conv(&peer),&len);
        if(newsockfd<0) return newsockfd;
        *peerPort = ntohs(peer.sin_port);
        *peerIp = inet_ntoa(peer.sin_addr);
        return newsockfd;
    }
};